package com.sn.author.monitor.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sn.author.common.context.SpringContext;
import com.sn.author.common.enums.CollectionStatusEnum;
import com.sn.author.common.enums.TaskEnums;
import com.sn.author.common.sdk.AbstractResponse;
import com.sn.author.common.sdk.response.CollectionResponse;
import com.sn.author.dao.ImportAccountMapper;
import com.sn.author.domain.entity.CollectionData;
import com.sn.author.domain.entity.ImportAccount;
import com.sn.author.domain.entity.JobAccount;
import com.sn.author.domain.taskEntity.TaskModel;
import com.sn.author.domain.vo.CollectionVo;
import com.sn.author.service.dao.CollectionService;
import com.sn.author.utils.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.NonNull;

import java.util.*;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * @Author xiaom
 * @Date 2020/10/26 10:30
 * @Version 1.0.0
 * @Description <>
 **/
@Slf4j
public class CollectionHandler extends AbsHandler {

    public CollectionHandler(TaskModel taskModel) {
        super(taskModel);
    }

    @Override
    AbstractResponse requestApi() {
        JobAccount jobAccount = JSON.parseObject(taskModel.getTaskParam().toString(),JobAccount.class);
        ImportAccountMapper importAccountMapper = SpringContext.getBean(ImportAccountMapper.class);

        String num = JSON.parseObject(jobAccount.getExecuteParams(),new TypeReference<HashMap<String,String>>(){}).get("collectionNum");

        //获取账号信息
        ImportAccount account = importAccountMapper.selectByPrimaryKey(Long.parseLong(jobAccount.getAccount() + ""));
        log.info("开始执行数据采集 采集条数:{}",num);
//        String param = "&os_api=23&device_type=Le%20X620&ssmix=a&manifest_version_code=110100&dpi=420&uuid=null18224449005&app_name=douyin_lite&version_name=11.1.0&ts=1605069513&app_type=normal&ac=wifi&update_version_code=11109902&channel=xinyou_dylite_and19&_rticket=1605069512807&device_platform=android&iid=2831975650695320&version_code=110100&mac_address=9f%3Ac4%3A41%3A9c%3A78%3Ae3&cdid=980d1fdc-1cbd-4d8d-8117-544afa27cd56&openudid=ace4ddef3ede8fd9&device_id=474622719719326&resolution=1080*1920&os_version=6.0&language=zh&device_brand=LeEco&aid=2329";
//        String header = "[{\"first\":\"Cookie\",\"second\":\"install_id=2831975650695320; ttreq=1$7a9a3c5db266615e2664f66ab4727fca77a72986; passport_csrf_token=7635b2b16bdd0e90f66debb47c55ac63; d_ticket=6b401d272c256bde3d4898c7189aacb537525; odin_tt=841890cf364126a71d3e9c3ef2757ed2a8230886bdd16f0285a47c32691fdf9dcfd6cabb061937cdde431f9eb454c113; n_mh=x-gLP_UfgWcLxazLlud4f8wYEwKKQxI0GigtKqcN838; sid_guard=d03a4b79c18ac8baba51ed5fde8467d8%7C1605069513%7C5184000%7CSun%2C+10-Jan-2021+04%3A38%3A33+GMT; uid_tt=33a8b8b97a5c26a2581cc8e3de630c1c; uid_tt_ss=33a8b8b97a5c26a2581cc8e3de630c1c; sid_tt=d03a4b79c18ac8baba51ed5fde8467d8; sessionid=d03a4b79c18ac8baba51ed5fde8467d8; sessionid_ss=d03a4b79c18ac8baba51ed5fde8467d8\"},{\"first\":\"X-SS-REQ-TICKET\",\"second\":\"1605069512805\"},{\"first\":\"X-Tt-Token\",\"second\":\"00d03a4b79c18ac8baba51ed5fde8467d8f3ac127c979b6998e32495490f5021ba3cf501dd669970f646a68bc7fd04baf025\"},{\"first\":\"sdk-version\",\"second\":\"1\"}]";
        account.setHeader(account.getHeader());
        account.setUrlParam(account.getUrlParam());
        return getSdkService().executeCollection(Integer.parseInt(num),account.getAreaCode(),jobAccount.getTaskId(),account.getHeader(),account.getUrlParam());
    }

    @Override
    String getSuccessMessage() {
        return "开始采集任务...";
    }

    @Override
    String getErrorMessage(String errmsg) {
        return "开启采集任务失败 失败信息:" + errmsg;
    }

    @Override
    public void responseAfter(@NonNull AbstractResponse response) {
        //更新任务状态
        String taskId = this.taskModel.getTaskId();
        CollectionService collectionService = getCollectionService();
        CollectionResponse collectionResponse = (CollectionResponse)response;
        CollectionResponse.ResponseMsgResult responseMsgResult = collectionResponse.getData();
        List<CollectionVo> list = responseMsgResult.getRows();
        if(list.isEmpty()){
            log.error("采集到的数据为空 taskId:{}",taskId);
            return;
        }

        //去重
        List<CollectionVo> unique = list.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(Comparator.comparing(CollectionVo::getUid))),
                        ArrayList::new)
        );

        List<CollectionData> insertData = BeanUtils.coventObject(unique, CollectionData.class);
        insertData.forEach(item -> item.setTaskId(Long.parseLong(taskId)));
        collectionService.saveCommitData(insertData);
        collectionService.updateTaskStatus(taskId, CollectionStatusEnum.FINISH);
    }

    @Override
    boolean isPushMessage() {
        return false;
    }

    @Override
    public void responseErrAfter(String errMsg) {
        //更新任务状态
        String taskId = this.taskModel.getTaskId();
        CollectionService collectionService = getCollectionService();
        collectionService.updateTaskStatus(taskId,CollectionStatusEnum.FAILED);
    }
}
